package com.xinqi.modules.exam.paper.manager.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.google.common.collect.ImmutableList;
import com.xinqi.common.base.dto.QuestionBaseDTO;
import com.xinqi.common.base.error.CommonErrors;
import com.xinqi.common.mybatis.data.service.impl.BaseServiceImpl;
import com.xinqi.common.redis.utils.Caches;
import com.xinqi.modules.exam.common.constants.ExamConstants;
import com.xinqi.modules.exam.paper.domain.CourseExamPaperEntity;
import com.xinqi.modules.exam.paper.dto.req.CourseExamPaperQueryDTO;
import com.xinqi.modules.exam.paper.dto.rsp.CourseExamPaperResultDTO;
import com.xinqi.modules.exam.paper.dto.rsp.CourseExamPaperStatusNumDTO;
import com.xinqi.modules.exam.paper.dto.rsp.CourseExamPaperStudentDTO;
import com.xinqi.modules.exam.paper.enums.ExamStatusEnum;
import com.xinqi.modules.exam.paper.manager.CourseExamPaperManager;
import com.xinqi.modules.exam.paper.mapper.CourseExamPaperMapper;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * 课程测评管理层实现
 *
 * @author: linkai
 * @date: 2023/07/02
 */
@Service
@RequiredArgsConstructor
public class CourseExamPaperManagerImpl extends BaseServiceImpl<CourseExamPaperMapper, CourseExamPaperEntity> implements CourseExamPaperManager {
    private final RedissonClient redissonClient;

    /**
     * 自定义分页查询
     */
    @Override
    public Page<CourseExamPaperResultDTO> findPage(Page<Object> page, CourseExamPaperQueryDTO query) {
        return this.baseMapper.findPage(page, query);
    }

    /**
     * 自定义列表查询
     */
    @Override
    public List<CourseExamPaperResultDTO> findList(CourseExamPaperQueryDTO query) {
        return this.baseMapper.findList(query);
    }

    /**
     * 查询 课程测评数据 -- 学生端
     */
    @Override
    public List<CourseExamPaperStudentDTO> findStudentList(CourseExamPaperQueryDTO dto) {
        return this.baseMapper.findStudentList(dto);
    }

    /**
     * 查询 课程测评数据 -- 学生端
     */
    @Override
    public Page<CourseExamPaperStudentDTO> pageStudentList(Page<Object> page, CourseExamPaperQueryDTO dto) {
        return this.baseMapper.pageStudentList(page, dto);
    }

    /**
     * 根据id查询 课程测评数据
     */
    @Override
    public CourseExamPaperEntity findById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), "ID不能为空");
        return Caches.get(() -> getById(id), redissonClient, ExamConstants.EXAM_KEY, id);
    }

    /**
     * 根据id查询 课程测评数据
     */
    @Override
    public QuestionBaseDTO findQuestionById(Long id, Long questionId) {
        CourseExamPaperEntity entity = findById(id);
        return findQuestionById(entity, questionId);
    }

    /**
     * 根据id查询 课程测评数据
     */
    @Override
    public QuestionBaseDTO findQuestionById(CourseExamPaperEntity entity, Long questionId) {
        if (entity == null) {
            return null;
        }
        return entity.getQuestionContent().stream()
            .filter(v -> Objects.equals(v.getId(), questionId))
            .findFirst().orElse(null);
    }

    @Override
    public CourseExamPaperEntity findBaseById(Long id) {
        if (id == null) {
            return null;
        }
        CourseExamPaperEntity entity = findById(id);
        if (entity == null) {
            return null;
        }
        entity.setQuestionContent(null);
        return entity;
    }

    @Override
    public ExamStatusEnum findStatusById(Long id) {
        CourseExamPaperEntity entity = findBaseById(id);
        if (entity == null) {
            return null;
        }
        return entity.getStatus();
    }

    @Override
    public Boolean isExists(Long id) {
        if (id == null) {
            return false;
        }
        LambdaQueryWrapper<CourseExamPaperEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CourseExamPaperEntity::getId, id);
        return count(wrapper) > 0;
    }

    /**
     * 根据id更新 课程测评数据，重写
     */
    @Override
    public boolean updateById(CourseExamPaperEntity entity) {
        boolean b = SqlHelper.retBool(getBaseMapper().updateById(entity));
        if (b) {
            try {
                // 清理缓存
                Caches.del(redissonClient, ExamConstants.EXAM_KEY, entity.getId());
            } catch (Exception ignored) {
            }
        }
        return b;
    }

    /**
     * 根据id更新 状态
     */
    @Override
    public boolean updateStatusById(Long id, ExamStatusEnum status) {
        if (Objects.isNull(id) || Objects.isNull(status)) {
            return false;
        }
        CourseExamPaperEntity entity = new CourseExamPaperEntity();
        entity.setId(id);
        entity.setStatus(status);
        return updateById(entity);
    }

    /**
     * 根据id删除 课程测评数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), "ID不能为空");
        return deleteByIds(ImmutableList.of(id));
    }

    /**
     * 根据id删除 课程测评数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteByIds(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return false;
        }
        boolean b = this.removeByIds(ids);
        if (b) {
            try {
                // 清理缓存
                ids.forEach(id -> Caches.del(redissonClient, ExamConstants.EXAM_KEY, id));
            } catch (Exception ignored) {
            }
        }
        return b;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByIdAndStatus(CourseExamPaperEntity entity) {
        LambdaUpdateWrapper<CourseExamPaperEntity> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(CourseExamPaperEntity::getId, entity.getId());
        wrapper.eq(CourseExamPaperEntity::getStatus, entity.getStatus());
        boolean b = this.baseMapper.update(entity, wrapper) > 0;
        if (b) {
            try {
                Caches.del(redissonClient, ExamConstants.EXAM_KEY, entity.getId());
            } catch (Exception ignored) {
            }
        }
        return b;
    }

    @Override
    public CourseExamPaperStatusNumDTO findStatusNum(Long classId) {
        if (classId == null) {
            return null;
        }
        CourseExamPaperStatusNumDTO statusNum = this.baseMapper.findStatusNum(classId);
        if (statusNum != null) {
            statusNum.init();
        }
        return statusNum;
    }

    @Override
    public CourseExamPaperStatusNumDTO findStudentStatusNum(Long classId, Long studentId) {
        if (classId == null) {
            return null;
        }
        CourseExamPaperStatusNumDTO statusNum = this.baseMapper.findStudentStatusNum(classId, studentId);
        if (statusNum != null) {
            statusNum.init();
        }
        return statusNum;
    }


}
